import React, { FC, useState } from 'react';
import {
  FormPanel,
  FormPanelType,
  InputType,
  type FormPanelObject,
  FormPanelBtnAlign,
  StandUploadExcel,
  Utils,
} from 'lfun-bg-comp';
import { Breadcrumb, Button, Table, TableProps, Space, message, Modal, Flex, Cascader } from 'antd';
import _ from 'lodash';
import { useNavigate } from 'react-router-dom';
import CloseReson from '../component/closeReson';
import Create from './create';
import { PageContainer } from '@/component/page-container';
import {
  KG_ORDER_STATUS,
  KG_LEVEL,
  FOUNDER_TYPE,
  SCHOOL_OPERATION_TYPE,
  SCHOOL_NATURE,
  SCHOOL_ORG_TYPE,
  TOWN_NATURE,
} from '@/constant/schoolOptions';
import { PAGINATIONCONFIG } from '@/constant/page';
import {
  buildPageItemTxtByEduType,
  getPagePath,
  getPathRoot,
  findLabelDeep,
  get_stoge_pz,
  set_stoge_pz,
} from '@/utils';
//import ImportExcel from '@/component/importExcel';
import styles from './index.less';
import {
  ClosePlanningSchool,
  SearchPlanningSchool,
  closePlanningSchool,
  //closePlanningSchool,
  deletePlanningSchool,
  importPlanningSchool,
  searchPlanningSchool,
} from '@/service/unit/planning';
import { IMPORT_EXCEL_TEMPLATE } from '@/constant';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';
import useCountry from '@/hooks/useCountry';
import { getPlanningSchoolCategoryOptions, getPlanningSchoolOperationTypeOptions } from '@/service/options';
import { YES_NO } from '@/constant/basicOptions';
import SelectList from './component/select-list';
import SelectList2 from './component/select-list2';

const storage_page_size_key = 'planning-idx-page-size';
const Groups: FC = () => {
  const isSchool = Utils.getProps('isSchool');
  // state
  const [current, setCurrent] = React.useState();
  const [dataSource, setDataSource] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz());
  const [pageIndex, setPageIndex] = React.useState(1);
  const [form, setForm] = React.useState(null);
  const [showCloseResone, setShowCloseResone] = React.useState(false);
  const [showCreateKG, setShowCreateKG] = React.useState(false);
  //const [showImportModel, setShowImporttModel] = React.useState(false);
  const [tableLoading, setTableLoading] = React.useState(false);
  const navigate = useNavigate();
  const country = useCountry();
  const [isHide, setIsHide] = useState(true);

  const searchTemplate: FormPanelType[] = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      inputs: [
        {
          label: `${buildPageItemTxtByEduType('园所名称')}（规划口径）`,
          name: 'planning_school_name',
          key: 'planning_school_name',
          textRange: [0, 20],
        },
        {
          label: '行政归属地',
          name: 'borough',
          key: 'borough',
          inputType: InputType.children,
          children: <SelectList />,
          span: 16,
          props: {
            labelCol: { span: 4 },
            wrapperCol: { span: 20 },
          },
        },
        {
          label: '状态',
          name: 'status',
          key: 'status',
          inputType: InputType.select,
          renderOption: KG_ORDER_STATUS,
        },
        {
          label: buildPageItemTxtByEduType('机构编码'),
          name: 'planning_school_no',
          key: 'planning_school_no',
          inputType: InputType.text,
          textRange: [0, 20],
        },
        {
          label: '星级',
          name: 'planning_school_level',
          key: 'planning_school_level',
          inputType: InputType.select,
          hidden: Utils.getProps('edu_type') !== 'kg',
          renderOption: KG_LEVEL,
        },
        {
          label: '学校性质',
          name: 'planning_school_edu_level',
          key: 'planning_school_edu_level',
          inputType: InputType.select,
          renderOption: SCHOOL_OPERATION_TYPE,
        },
        {
          label: '办学类型分组',
          name: 'planning_school_category',
          key: 'planning_school_category',
          inputType: InputType.select,
          renderOption: async (form: FormPanelObject) => {
            return getPlanningSchoolCategoryOptions(form, 'planning_school_edu_level');
          },
        },
        {
          label: '办学类型',
          name: 'planning_school_operation_type',
          key: 'planning_school_operation_type',
          renderOption: SCHOOL_OPERATION_TYPE,
          inputType: InputType.cascader,
          children: <Cascader />,
        },
        {
          label: '举办者类型',
          name: 'founder_type',
          key: 'founder_type',
          inputType: InputType.cascader,
          renderOption: FOUNDER_TYPE,
          inputProps: {
            multiple: true,
          },
          hidden: isHide,
        },
        {
          label: buildPageItemTxtByEduType('园所代码'),
          name: 'planning_school_code',
          key: 'planning_school_code',
          inputType: InputType.text,
          textRange: [0, 20],
          hidden: isHide,
        },
        {
          label: '是否普惠性幼儿园',
          name: 'aaa',
          key: 'aaa',
          inputType: InputType.select,
          renderOption: YES_NO,
          hidden: isHide,
        },
        {
          label: '是否乡镇幼儿园',
          name: 'a11',
          key: 'a11',
          inputType: InputType.select,
          renderOption: YES_NO,
          hidden: isHide,
        },
        {
          label: '建校年月',
          name: 'create_planning_school_date',
          key: 'create_planning_school_date',
          inputProps: {
            picker: 'month',
          },
          inputType: InputType.date,
          hidden: isHide,
        },
        {
          label: '法定代表人',
          name: 'b',
          key: 'b',
          textRange: [0, 20],
          hidden: isHide,
        },
        {
          label: '统一社会信用代码',
          name: 'social_credit_code',
          key: 'social_credit_code',
          textRange: [0, 50],
          hidden: isHide,
        },
        {
          label: '办别',
          name: 'planning_school_org_type',
          key: 'planning_school_org_type',
          inputType: InputType.select,
          renderOption: SCHOOL_ORG_TYPE,
          hidden: isHide,
        },
        {
          label: '所在地城乡性质',
          name: 'urban_rural_nature',
          key: 'urban_rural_nature',
          inputType: InputType.cascader,
          renderOption: TOWN_NATURE,
          formatSubmitValue: value => {
            if (_.isArray(value)) {
              return value.join(',');
            }
            return value;
          },
          formatValue: value => {
            if (_.isString(value)) {
              return value.split(',');
            }
            return value;
          },
          hidden: isHide,
        },
        {
          label: '所在地址',
          name: 'a',
          key: 'a',
          inputType: InputType.children,
          children: <SelectList2 />,
          span: 24,
          props: {
            labelCol: { span: 2 },
            wrapperCol: { span: 20 },
          },
          hidden: isHide,
        },
      ],
    },
  ];
  const columns: TableProps['columns'] = [
    {
      title: '编号',
      width: 100,
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      fixed: 'left',
      render(val, row, index) {
        return index + 1;
      },
    },

    {
      title: buildPageItemTxtByEduType('园所名称(学校)'),
      width: 500,
      dataIndex: 'planning_school_name',
      key: 'planning_school_name',
      align: 'center',
      fixed: 'left',
      render: (text: any) => {
        return <div style={{ color: '#1677ff' }}>{text}</div>;
      },
    },
    {
      title: buildPageItemTxtByEduType('机构编码'),
      width: 100,
      dataIndex: 'planning_school_no',
      key: 'planning_school_no',
      align: 'center',
    },
    {
      title: buildPageItemTxtByEduType('园所代码'),
      width: 100,
      dataIndex: 'planning_school_code',
      key: 'planning_school_code',
      align: 'center',
    },
    {
      title: '行政归属地',
      width: 150,
      dataIndex: 'borough',
      key: 'borough',
      align: 'center',
      render: (text: any) => {
        return _.find(country, { value: String(text) })?.label;
      },
    },
    // {
    //   title: '地域管辖区',
    //   width: 150,
    //   dataIndex: 'block',
    //   key: 'block',
    //   align: 'center',
    //   render: (text: any) => {
    //     return _.find(country, { value: String(text) })?.label;
    //   },
    // },
    {
      title: '举办者类型',
      width: 300,
      dataIndex: 'founder_type',
      key: 'founder_type',
      align: 'center',
      render: (text: any) => {
        const arr: any[] = [];
        if (_.isArray(text)) {
          text.forEach(v => {
            const label = findLabelDeep(FOUNDER_TYPE, String(v));
            if (label) {
              arr.push(label);
            }
          });
        }
        return arr.join('/');
      },
    },
    {
      title: buildPageItemTxtByEduType('园所星级'),
      dataIndex: 'planning_school_level',
      key: 'planning_school_level',
      align: 'center',
      width: 100,
      render: (text: any) => {
        return _.find(KG_LEVEL, { value: String(text) })?.label;
      },
    },
    {
      title: '学校性质',
      dataIndex: 'planning_school_edu_level',
      key: 'planning_school_edu_level',
      align: 'center',
      width: 100,
      render: (text: any) => {
        return _.find(SCHOOL_OPERATION_TYPE, { value: String(text) })?.label;
      },
    },
    {
      title: '办学类型分组',
      dataIndex: 'planning_school_category',
      key: 'planning_school_category',
      align: 'center',
      width: 200,
      render: (text: any, record: any) => {
        const res = _.find(SCHOOL_OPERATION_TYPE, { value: record.planning_school_edu_level });
        if (res) {
          return _.find(res.children, { value: String(text) })?.label;
        }
        return text;
      },
    },
    {
      title: '办学类型',
      dataIndex: 'planning_school_operation_type',
      key: 'planning_school_operation_type',
      width: 100,
      align: 'center',
      render: (text: any, record: any) => {
        const edu_level_res = _.find(SCHOOL_OPERATION_TYPE, { value: record.planning_school_edu_level });
        if (edu_level_res) {
          const res = _.find(edu_level_res.children, { value: String(record.planning_school_category) });
          if (res) {
            return _.find(res.children, { value: String(text) })?.label;
          }
        }
        return text;
      },
    },
    // {
    //   title: '办学类型',
    //   dataIndex: 'planning_school_operation_type',
    //   key: 'planning_school_operation_type',
    //   width: 100,
    //   align: 'center',
    //   render: (text: any) => {
    //     const arr: any[] = [];
    //     if (_.isArray(text)) {
    //       text.forEach(v => {
    //         const label = utils.findLabelDeep(SCHOOL_OPERATION_TYPE, String(v));
    //         if (label) {
    //           arr.push(label);
    //         }
    //       });
    //     }
    //     return arr.join('/');
    //   },
    // },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      key: 'status',
      align: 'center',
      render: (text: any) => {
        return _.find(KG_ORDER_STATUS, { value: text })?.label;
      },
    },
    {
      title: '操作',
      dataIndex: 'op',
      key: 'op',
      //width: 220,
      fixed: 'right',
      align: 'center',
      // hidden: !isPermissionOperate(),
      render: (text, record) => {
        return (
          <Space>
            <Button
              key="look"
              type="link"
              size="small"
              onClick={() => navigate(`${getPathRoot()}/planning/details/${record.id}`, { state: { ...record } })}
            >
              查看
            </Button>
            <Button
              key="edit"
              type="link"
              size="small"
              onClick={() => {
                navigate(`${getPathRoot()}/planning/edit/${record.id}`, { state: { ...record } });
              }}
            >
              编辑
            </Button>
            <Button
              key="change"
              type="link"
              size="small"
              onClick={() => {
                navigate(`${getPathRoot()}/planning/change/${record.id}`, { state: { ...record } });
              }}
            >
              变更
            </Button>
            <Button
              key="close"
              type="link"
              size="small"
              onClick={() => {
                setShowCloseResone(true);
                setCurrent(record.id);
              }}
            >
              关闭
            </Button>
            <PermissionButton permission="view">
              <Button
                key="look"
                type="link"
                size="small"
                onClick={() => navigate(`${getPathRoot()}/planning/details/${record.id}`, { state: { ...record } })}
              >
                查看
              </Button>
            </PermissionButton>
            {['draft', 'opening'].includes(record.status) && record.workflow_status !== 'needaudit' ? (
              <PermissionButton permission="edit">
                <Button
                  key="edit"
                  type="link"
                  size="small"
                  onClick={() => {
                    navigate(`${getPathRoot()}/planning/edit/${record.id}`, { state: { ...record } });
                  }}
                >
                  编辑
                </Button>
              </PermissionButton>
            ) : (
              ''
            )}
            {['normal'].includes(record.status) && record.workflow_status !== 'needaudit' ? (
              <PermissionButton permission="change">
                <Button
                  key="change"
                  type="link"
                  size="small"
                  onClick={() => {
                    navigate(`${getPathRoot()}/planning/change/${record.id}`, { state: { ...record } });
                  }}
                >
                  变更
                </Button>
              </PermissionButton>
            ) : (
              ''
            )}
            {record.status === 'normal' && record.workflow_status !== 'needaudit' ? (
              <PermissionButton permission="close">
                <Button
                  key="close"
                  type="link"
                  size="small"
                  onClick={() => {
                    setShowCloseResone(true);
                    setCurrent(record.id);
                  }}
                >
                  关闭
                </Button>
              </PermissionButton>
            ) : (
              ''
            )}
            {record.status === 'draft' && record.workflow_status !== 'needaudit' ? (
              <PermissionButton permission="delete">
                <Button
                  type="link"
                  size="small"
                  key="delete"
                  onClick={() => {
                    Modal.confirm({
                      title: '删除',
                      content: `确定否删除‘${record.planning_school_name}’的相关信息`,
                      onOk: async () => {
                        const r = await deletePlanningSchool(record.id);
                        if (r?.success) {
                          message.success('删除成功');
                          search(form?.getFieldsValue(), pageSize, pageIndex);
                        } else {
                          throw new Error();
                        }
                      },
                    });
                  }}
                >
                  删除
                </Button>
              </PermissionButton>
            ) : (
              ''
            )}
            {/* { ['draft', 'opening'].includes(record.status) && record.workflow_status !== 'needaudit' ? (
              <Button
                key="opening"
                type="link"
                size="small"
                onClick={() => navigate(`${getPathRoot()}/planning/edit/${record.id}`, { state: { ...record } })}
              >
                正式开办
              </Button>
            ) : (
              ''
            )} */}
            <PermissionButton permission="relation">
              <Button
                key="look"
                type="link"
                size="small"
                onClick={() => navigate(`${getPathRoot()}/school?planning_school_id=${record.id}`)}
              >
                关联学校
              </Button>
            </PermissionButton>
          </Space>
        );
      },
    },
  ];
  const buildBtns = () => {
    return [
      <Button type="link" onClick={() => setIsHide(!isHide)}>
        {isHide ? '展开' : '收起'}
      </Button>,
      <PermissionButton permission="export">
        <Button type="primary" key="export">
          导出
        </Button>
      </PermissionButton>,
    ];
  };

  const search = async (params: any, pageSize, pageIndex) => {
    if (tableLoading) {
      return;
    }
    setTableLoading(true);
    const searchParams: SearchPlanningSchool = {
      ...params,
    };
    if (params.founder_type && params.founder_type.length > 0) {
      const fouder_type_set1 = new Set<string>();
      const fouder_type_set2 = new Set<string>();
      const fouder_type_set3 = new Set<string>();
      params.founder_type.forEach(item => {
        if (item.length > 2) fouder_type_set3.add(item[2]);
        else if (item.length > 1) fouder_type_set2.add(item[1]);
        else if (item.length > 0) fouder_type_set1.add(item[0]);
      });
      searchParams.founder_type = Array.from(fouder_type_set1);
      searchParams.founder_type_lv2 = Array.from(fouder_type_set2);
      searchParams.founder_type_lv3 = Array.from(fouder_type_set3);
    }
    const { success, data } = await searchPlanningSchool(searchParams, pageIndex, pageSize);
    if (success) {
      setDataSource(
        data?.items?.map((v, i) => {
          v.key = i;
          v.founder_type = [v.founder_type, v.founder_type_lv2, v.founder_type_lv3];
          // v.planning_school_operation_type = [
          //   v.planning_school_operation_type,
          //   v.planning_school_operation_type_lv2,
          //   v.planning_school_operation_type_lv3,
          // ];
          return v;
        })
      );
      setTotal(data.total);
      setPageSize(pageSize);
      setPageIndex(pageIndex);
      setTableLoading(false);
    }
  };

  const pageChange = (pageIndex, pageSize) => {
    set_stoge_pz(pageSize);
    search(form?.getFieldsValue(), pageSize, pageIndex);
  };

  React.useEffect(() => {
    search({}, pageSize, 1);
  }, []);

  return (
    <PageContainer header={<Breadcrumb items={[{ title: getPagePath().power_name }]} />}>
      <FormPanel
        template={searchTemplate}
        key={1}
        submitBtnText="搜索"
        restBtnText="重置"
        btnsAlign={FormPanelBtnAlign.right}
        buttons={buildBtns()}
        onLoad={form => setForm(form)}
        onReset={(formPanelObject: FormPanelObject) => {
          formPanelObject.resetFields();
          search({}, pageSize, 1);
        }}
        onFinish={(formPanelObject: FormPanelObject) => {
          const params = formPanelObject.getFieldsValue();
          console.log(params);

          search(params, pageSize, 1);
          setForm(form);
          return false;
        }}
      />
      <Flex gap="small" wrap="wrap" style={{ marginBottom: 20 }}>
        {!isSchool && (
          <PermissionButton permission="import">
            <StandUploadExcel
              uploadSrv="/school/v1/storage/school-upload-uri"
              templateUrl={IMPORT_EXCEL_TEMPLATE.planning_school}
              templateName="资源导入模版.xlsx"
              showExcelSrv="/school/v1/storage/file-data-preview"
              scene="planning_school"
              onImport={async (data, file_name, bucket_name) => {
                const res = await importPlanningSchool({
                  file_name,
                  bucket_name,
                  scene: 'planning_school',
                });
                if (res.success) {
                  message.success('导入成功');
                  search({}, pageSize, 1);
                  return true;
                }
                message.error(res.message || res.details);
                return false;
              }}
            >
              导入
            </StandUploadExcel>
          </PermissionButton>
        )}

        <Button key="openkg" type="primary" onClick={() => setShowCreateKG(true)}>
          {buildPageItemTxtByEduType('开办园所（规划口径）')}
        </Button>
        {!isSchool && (
          <PermissionButton permission="open">
            <Button key="openkg" type="primary" onClick={() => setShowCreateKG(true)}>
              {buildPageItemTxtByEduType('开办园所（规划口径）')}
            </Button>
          </PermissionButton>
        )}
      </Flex>
      <Table
        className={styles.table}
        dataSource={dataSource}
        columns={
          Utils.getProps('edu_type') === 'kg' ? columns : columns.filter(it => it.key !== 'planning_school_level')
        }
        scroll={{ x: 'max-content' }}
        loading={tableLoading}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
      <CloseReson
        show={showCloseResone}
        onCancel={(formPanelObject: FormPanelObject) => {
          formPanelObject.resetFields();
          setShowCloseResone(false);
        }}
        onOk={async (formPanelObject: FormPanelObject) => {
          const values = formPanelObject.getFieldsValue();
          const closeParams: ClosePlanningSchool = {
            planning_school_id: current,
            ...values,
          };
          //console.log(closeParams, '=====================>>>>');
          const res = await closePlanningSchool(closeParams);
          if (res.success) {
            message.success('关闭成功');
            setShowCloseResone(false);
            search(form?.getFieldsValue(), pageSize, pageIndex);
            form.resetFields();
          } else {
            formPanelObject.reVaildation(res);
          }
        }}
      />
      <Create
        show={showCreateKG}
        onCancel={() => setShowCreateKG(false)}
        onOk={() => {
          search(form?.getFieldsValue(), pageSize, pageIndex);
        }}
      />
      {/* TODO: templateUrl 需要提供 */}
      {/* <ImportExcel
        templateUrl=""
        getExcelSrv="/getExcel"
        show={showImportModel}
        onImport={data => {
          console.log(data);
        }}
        onCancel={() => setShowImporttModel(false)}
      /> */}
    </PageContainer>
  );
};

export default Groups;
